<template>
    <div class="file_box">
        <!-- 文件上传 -->
        <div class="d-flex flex-wrap" v-if="type == 'file'">
            <div>
                <el-upload
                        ref="upload"
                        :show-file-list="false"
                        class="upload-demo m-l10"
                        :http-request="upload"
                        :on-remove="onRemove"
                        :disabled="disabled"
                        :on-exceed="onExceedHandel"
                >
                    <template #trigger>
                        <el-button
                                :disabled="disabled"
                                v-if="showButton"
                                class="btn_class"
                                style="color: #fc7018; border: 1px solid #fc7018"
                                plain
                                color="#fff8f6"
                        >
                            <svg-icon
                                    icon-class="project-detail-icon-l-shangchuan"
                                    class="icon"
                            />
                            上传文件</el-button
                        >
                    </template>
                </el-upload>
            </div>
            <div class="filesContent d-flex">
                <div class="files_c_item m-b10" v-for="(v, i) in files" :key="i">
                    <el-icon
                            color="#999999"
                            v-if="!disabled"
                            @click="handelFileDelete(v)"
                            class="icon_delete"
                    >

                        <CircleCloseFilled />
                    </el-icon>
                    <span class="icon_name" @click="handelFileDown(v)"
                    ><el-icon> <Document  /> </el-icon>{{ v.fileName }}</span
                    >
                </div>
            </div>
        </div>

        <!-- 图片上传 -->
        <div class="d-flex" v-if="type == 'img'">
            <div class="d-flex filesContent_img" v-for="(v, i) in files" :key="i">
                <div
                        class="files_c_item_img m-r20"
                        @mouseenter="isShow[i] = true"
                        @mouseleave="isShow[i] = false"
                >
                    <el-icon class="icon_delete"  v-if="!disabled" @click.stop="handelFileDelete(v)"
                    ><CircleCloseFilled
                    /></el-icon>
                    <el-icon
                            v-show="isShow[i]"
                            class="icon_preview"
                            @click.stop="handlePictureCardPreview(v)"
                    ><CirclePlus
                    /></el-icon>

                    <el-icon
                            v-show="isShow[i]"
                            class="icon_down"
                            @click.stop="handelFileDown(v)"
                    ><Download
                    /></el-icon>
                    <img :src="dialogImageUrl" alt="" />
                </div>
            </div>
            <div v-if="restrictionLimit != files.length">
                <el-upload
                        ref="upload"
                        :show-file-list="false"
                        class="upload-img"
                        :http-request="upload"
                        :on-preview="handlePictureCardPreview"
                        list-type="picture-card"
                        :disabled="disabled"
                        :on-exceed="onExceedHandel"
                >
                    <el-icon><Plus /></el-icon>
                </el-upload>
            </div>
        </div>
        <div v-if="restriction && showButton" class="restriction m-t10">
            限制上传数量: <span>{{ restrictionLimit }}</span>
        </div>
    </div>

    <el-dialog v-model="dialogVisible">
        <img style="width: 100%" w-full :src="dialogImageUrl" alt="图片预览" />
    </el-dialog>
</template>

<script setup>
import { ElUpload, ElLoading, ElMessage, ElIcon, ElDialog } from 'element-plus'
import { ref, watch } from 'vue'
import {
    Document,
    CircleCloseFilled,
    Plus,
    CirclePlus,
    Download
} from '@element-plus/icons-vue'
import { fileCallback } from '@/api/common.js'
import { fileControlApi } from '@/api/assets'
import {fileApi} from "@/api/investment";
import axios from "axios";
const props = defineProps({
    showButton:{
        type: Boolean,
        default: true
    },
    disabled: {
        type: Boolean,
        default: false
    },
    /* 文件上传file 图片上传img */
    type: {
        type: String,
        default: 'file'
    },
    /* 上传参数 */
    /* 业务类型（1房源业务，2资产业务 11招标比选会审 12招标结果会审 13招标合同会审 14招标中标通知书 15招标合同扫描件） */
    businessType: {
        type: Number,
        default: 0
    },
    /* 关联编号id */
    associationId: {
        type: String,
        default: ''
    },

    files: {
        type: Array,
        default: []
    },
    /* 限制数量 */
    restriction: {
        type: Boolean,
        default: true
    },
    restrictionLimit: {
        type: Number,
        default: 99
    }
})

const emits = defineEmits(['updateFiles','update:files','onSuccess'])
const isShow = ref([])

// 下载
const handelFileDown = (item) => {
    let a = document.createElement('a')
    a.href = item.fileAddress
    a.download = item.fileName

    switch (item.fileName.split('.')[1]) {
        case 'pdf':
            a.target = '_blank'
            break
        case 'jpg':
            a.target = '_blank'
            break
        case 'bmp':
            a.target = '_blank'
            break
        case 'jpeg':
            a.target = '_blank'
            break
        case 'gif':
            a.target = '_blank'
            break
        case 'png':
            a.target = '_blank'
            break

        default:
            break
    }
    a.click(() => {
        return false
    })
    console.log(a.href);
    URL.revokeObjectURL(a.href)
    a.remove()
}
// 删除
const handelFileDelete = (item) => {
    let i = props.files.findIndex((v, i) => v.fileUrlKey != item.fileUrlKey);
    let list = JSON.parse(JSON.stringify(props.files));
    list.splice(i,1)
    ElMessage.success('删除成功!')
    emits('updateFiles', list)
    emits('update:files', list)
}
const dialogImageUrl = ref('')
const onRemove = () => {

}
const dialogVisible = ref(false)
const handlePictureCardPreview = (e) => {
    dialogImageUrl.value = e.fileAddress
    dialogVisible.value = true
}

const upload = async (file) => {
    if (props.files.length === props.restrictionLimit) {
        ElMessage.warning('文件上传数量超限制!')
        return;
    }

    //校验是否是图片
    if (props.type === 'img') {
        let types=['image/jpeg','image/png','image/gif','image/bmp','image/jpg']
        if(!types.includes(file.file.type)){
            ElMessage.warning('请上传图片!')
            return;
        }

    }
    const loading = ElLoading.service({
        lock: true,
        text: '上传中，请稍后',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    let config = {
        headers: {
            "Content-Type": "multipart/form-data"
        },
        onUploadProgress: (event) => {
            let progress = Math.round(event.loaded / event.total * 100) | 0;
            loading.setText(`上传中，请稍后...${progress}%`);
        },
    };


    let resFile = file.file;  //注意：直接上传file文件，不要用FormData对象的形式传
    const formData = new FormData();
    formData.append('file', resFile);

    const { code, data } = await fileApi.upload(formData);

    // // const res = await fileApi.getMinioAddress({fileName:resFile.name});
    if (code != '200'){
        loading.close();
        return  ElMessage.error("上传失败,请联系管理员!");
    }
    // //需要用put方法上传，post会报405，aws官方规定是put方法
    // const resData = await axios.put(result, resFile, config);
    if (code == 200) {
        // props.files.unshift({
        //     associationId: props.associationId,
        //     businessType: props.businessType,
        //     fileName: resFile.name,
        //     fileUrlKey: res.data.fileUrl,
        // })
        let list = JSON.parse(JSON.stringify(props.files || []));

        list.unshift({
            associationId: props.associationId,
            businessType: props.businessType,
            fileName: resFile.name,
            fileUrlKey: data,
            // fileAddress: res.data.fileAddress
            fileAddress: 'http://182.148.53.132:9000/gxsst/' + data
        })

        emits('updateFiles', list)
        emits('update:files', list)

        loading.close();

        ElMessage.success("上传成功!");
    }
    if(code != 200){
        loading.close();
        ElMessage.error("上传失败,请联系管理员!");
    }
}

const onExceedHandel = () => {
    ElMessage.warning('文件上传数量超限制!')
}
</script>
<style lang="scss" scoped>
.filesContent {
  align-items: center;
  flex-wrap: wrap;
  .files_c_item {
    min-width: 120px;
    padding: 0 30px;
    position: relative;

    .icon_delete {
      position: absolute;
      top: -10px;
      right: 0;
      cursor: pointer;
    }
    .icon_delete:hover {
      color: red;
    }

    .icon_name {
      color: #999;
      cursor: pointer;
    }
    .icon_name:hover {
      color: #fc7018;
    }
  }
}

.restriction {
  font-size: 12px;
  font-family: SourceHanSansCN-Normal, SourceHanSansCN;
  color: #f12527;
}

.upload-img {
  position: relative;
  width: 67px;
  height: 67px;
  .el-icon {
    color: #fc7018;
  }

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
    border: 1px solid #fc7018;
    background-color: #fff8f6;
  }
  .icon_delete {
    position: absolute;
    top: -10px;
    right: -10px;
    cursor: pointer;
  }
}

.filesContent_img {
  flex-wrap: wrap;
  .files_c_item_img {
    position: relative;
    width: 67px;
    height: 67px;
    border: 1px solid #fc7018;
    background-color: #fff8f6;
    border-radius: 5px;
    // cursor: pointer;
    text-align: center;
    line-height: 67px;
    img {
      position: absolute;
      width: 100%;
      z-index: 1;
      left: 0;
      top: 0;
      height: 100%;
      object-fit: cover;
    }
    .icon_delete {
      position: absolute;
      top: -8px;
      right: -8px;
      cursor: pointer;
      color: #fc7018;
      z-index: 3;
    }
    .icon_preview,
    .icon_down {
      cursor: pointer;
      color: #999;
      z-index: 3;
    }
    .icon_preview:hover,
    .icon_down:hover {
      color: #fc7018;
    }
  }
}

.file_box {
  min-height: 100px;
}
</style>
